<template>
  <div>
    <MyHead title="注册账号" :show="true"></MyHead>
    <van-form @submit="onSubmit" ref="registerform">
      <van-field
        v-model="register.phone"
        name="phone"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '请填写手机号' },{ pattern: phonePattern, message: '请输入正确手机号' }]"
      />
      <van-field
        v-model="register.username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="register.password"
        :type="type"
        name="password"
        label="登录密码"
        placeholder="6-12位字母加数字"
        :right-icon="type == 'password' ? 'closed-eye' : 'eye-o'"
        @click-right-icon="changeType"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: $reg.pwd, message: '请输入合法密码' },
        ]"
        @blur="checkDbpass"
      />
      <van-field
        v-model="register.dbpass"
        :type="type"
        name="dbpass"
        label="确认登录密码"
        placeholder="12位字母加数字"
        :rules="[
          { required: true, message: '请再次填写密码' },
          { pattern: $reg.pwd, message: '请输入合法密码' },
          {
            validator: checkPassEqual,
            message: '密码不一致',
          },
        ]"
      />
      <van-field
        name="agree"
        :rules="[{ required: true, message: '请勾选同意' }]"
      >
        <template #input>
          <van-checkbox v-model="register.agree"
            >请勾选同意用户协议</van-checkbox
          >
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >注册</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  name: "register",
  data() {
    return {
      register: {},
      phonePattern: this.$reg.phone,
      type: "password",
    };
  },
  methods: {
    onSubmit(val) {
      this.$ajax
        .register(val)
        .then((res) => {
          if (res.code == 200) {
            this.$router.push({ name: "login", query: { phone: val.phone } });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    checkPassEqual(val) {
      return this.register.password == val;
    },
    checkDbpass() {
      console.log(this.$reg);
      if (this.register.dbpass) {
        this.$refs.registerform.validate("dbpass"); //启动所有的校验
      }
    },
    changeType() {
      this.type = this.type == "password" ? "text" : "password";
    },
  },
};
</script>